const AV = require('../../libs/av-weapp-min.js');
//logs.js
var util = require('../../utils/util.js')
Page({
    data: {
        address: '222',
        imagelist: [],
        fieldnum: 1,
        charge: false,
        remark: '',
        latitude: 0,
        longitude: 0,

    },
    onLoad: function ({ address = '', latitude, longitude }) {
        this.setData({ address: address });
        this.setData({ latitude: latitude });
        this.setData({ longitude: longitude });
    },
    addImage: function () {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: ({ tempFilePaths }) => {
                let list = [];
                // // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                list = list.concat(this.data.imagelist, tempFilePaths).filter(x => x);
                console.log(list);
                this.setData({ 'imagelist': list });
            }
        })
    },
    inputdeal: function ({target: {dataset: {name}}, detail: {value}}) {
        this.setData({ [name]: value })
    },
    submit: function () {
        if (this.data.address.trim() === '') {
            return;
        }
        let user = wx.getStorageSync('user');

        var Site = AV.Object.extend('site');
        // 新建对象
        var site = new Site();

        this.data.imagelist.map(tempFilePath => () => new AV.File('filename', {
            blob: {
                uri: tempFilePath,
            },
        }).save()).reduce(
            (m, p) => m.then(v => AV.Promise.all([...v, p()])),
            AV.Promise.resolve([])
            ).then(files => files.map(file => file.url()))
            .then(images => {
                console.log(this.data);
                site.set('address', this.data.address);
                site.set('imagelist', images);
                site.set('fieldnum', parseInt(this.data.fieldnum));
                site.set('charge', this.data.charge);
                site.set('remark', this.data.remark);
                site.set('location', new AV.GeoPoint(parseFloat(this.data.latitude), parseFloat(this.data.longitude)));
                site.set('creater_id', user.id);
                site.set('creater_name', user.nickName);
                site.set('creater_avatar', user.avatarUrl);
                site.save().then(function (data) {
                    wx.showToast({
                        title: '添加成功',
                        duration: 2000
                    })
                    setTimeout(() => {
                        wx.navigateBack({
                            delta: 1
                        })
                    }, 2000)
                }, function (error) {
                    console.error(error);
                });
            }).catch(console.error);


    }
})

